package com.zkflzl.initbackendfileservice.controller;


import cn.hutool.core.io.FileUtil;
import com.zkflzl.initbackendcommon.common.BaseResponse;
import com.zkflzl.initbackendcommon.common.ErrorCode;
import com.zkflzl.initbackendcommon.exception.BusinessException;
import com.zkflzl.initbackendfileservice.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 文件接口
 *
 * @author <a href="https://gitee.com/zkflzl">zkflzl</a>
 */
@RestController
@RequestMapping("/")
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                   HttpServletRequest request) {

        // TODO 要登录吗?
        // userService.getLoginUser(request);   // 没登陆会抛 运行异常 全局捕捉到会返回前端 未登录 信息

        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 判断是否为 word 文档
        if (!Arrays.asList("doc","docx").contains(fileSuffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
        }

        return fileService.uploadToPDF(multipartFile);

    }
}
